
var currentRandomeString = MD5((Math.random() * 32452.2452) + "abc");

var randomString = function() {
	return currentRandomeString = MD5(currentRandomeString
			+ (Math.random() * 32452.2452) + "abc");
}

var subPub = new SubPub();
var ost = window.setTimeout;

// window.setTimeout = function() {
// console.log('window.setTimeout(' + arguments[0] + '\n)\n' + arguments[1]);
// try {
// ost.apply(window, arguments);
// } catch (e) {
// console.dir(e.stack || e);
// }
// }

var deliciousRe = /https?\:\/\/delicious.com\/(?!a\/)/;
var loadingAnimation;
var localSystem;
var remoteSystem;
var canvasRotater;
var flasher;
var bookmarkStorage = new BookmarkStorage();

var openWindow = function(url) {
	chrome.tabs.getAllInWindow(undefined, function(tabs) {
				for (var i = 0, tab; tab = tabs[i]; i++) {
					if (tab.url && tab.url == url) {
						chrome.tabs.update(tab.id, {
									selected : true
								});
						return;
					}
				}
				chrome.windows.create({
							url : url,
							width : 300,
							height : 500
						}, function() {
						});
			});
}
var deliciousSystems = {};

var getDeliciousBookmarSystem = function(username, password) {
	if (!deliciousSystems[username])
		deliciousSystems[username] = {};
	if (!deliciousSystems[username][password])
		deliciousSystems[username][password] = new DeliciousBookmarkSystem(
				username, password);
	return deliciousSystems[username][password];
}

var applyBookmark = function(original, xmlNode) {
	function a(n) {
		return xmlNode.getAttribute(n);
	};
	var urlMD5 = a('hash') || a('url');
	var url = a('href');
	var extended = a('extended');
	var meta = a('meta');
	var tag = a('tag');
	if (tag)
		tag = tag.split(' ');
	var time = a('time');

	if (urlMD5)
		original.urlMD5 = urlMD5;
	if (url)
		original.url = url;
	if (extended)
		original.extended = extended;
	if (meta)
		original.meta = meta;
	if (tag)
		original.tag = tag;
	if (time)
		original.time = time;

	return urlMD5 != null || url != null || extended != null || meta != null
			|| tag != null || time != null;
}

function linkEvents() {
	chrome.tabs.onUpdated.addListener(function(tabId, changeInfo) {
				if (changeInfo.url && deliciousRe.test(changeInfo.url)) {
					console.log("saw delicious! updating...");
				}
			});

	chrome.browserAction.onClicked.addListener(function(tab) {
				delicious.startRequest();
			});
}

var delicious;
function firstTimeUsing() {
	setTimeout(function() {
				chrome.windows.create({
							url : chrome.extension.getURL('pages/options.html')
						}, function() {
						});
			}, 100);
}

Date.prototype.setISO8601 = function(string) {
	var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})"
			+ "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?"
			+ "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
	var d = string.match(new RegExp(regexp));

	var offset = 0;
	var date = new Date(d[1], 0, 1);

	if (d[3]) {
		date.setMonth(d[3] - 1);
	}
	if (d[5]) {
		date.setDate(d[5]);
	}
	if (d[7]) {
		date.setHours(d[7]);
	}
	if (d[8]) {
		date.setMinutes(d[8]);
	}
	if (d[10]) {
		date.setSeconds(d[10]);
	}
	if (d[12]) {
		date.setMilliseconds(Number("0." + d[12]) * 1000);
	}
	if (d[14]) {
		offset = (Number(d[16]) * 60) + Number(d[17]);
		offset *= ((d[15] == '-') ? 1 : -1);
	}

	offset -= date.getTimezoneOffset();
	time = (Number(date) + (offset * 60 * 1000));
	this.setTime(Number(time));
}

function init() {

	if (!localStorage['already_used']) {
		localStorage['already_used'] = true;
		firstTimeUsing();
	}
	delete localStorage.cached_bookmarks;
	loadingAnimation = new LoadingAnimation();
	canvasRotater = new CanvasRotater();
	flasher = new Flasher();

	linkEvents();

	try {
		localSystem = new LocalBookmarkSystem();
		var stub = subPub.subscribe('local/load', function(args) {
					console.dir(args);
					if (args.jobId == id) {
						subPub.unsubscribe(stub);
						localSystem.listen();
					}
				});
		var id = localSystem.scheduleLoading();

	} catch (e) {
		console.dir(e.stack || e);
	}
	if (localStorage['username'] && localStorage['password']) {
		delicious = getDeliciousBookmarSystem(localStorage['username'],
				localStorage['password']);
		delicious.tryLogin();
	}
}

var d = function() {
	delicious.scheduleLoading();
}